// @algorithm @lc id=502 lang=cpp 
// @title ipo


// @test(2,0,[1,2,3],[0,1,1])=4
// @test(3,0,[1,2,3],[0,1,2])=6
class Solution {
public:
    int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
        int n = profits.size();
        vector<pair<int,int>> prj;
        for(int i=0; i<n; i++)
            prj.push_back({capital[i], profits[i]});
        sort(prj.begin(), prj.end()); // 项目成本升序
        auto p = prj.begin();
        
        priority_queue<int, vector<int>, less<int>> canDo; // 大顶堆：可做项目的收益
        for(int i=0; i<k; i++){
            while(p!=prj.end() && p->first<=w){ // 找出可做项目
                canDo.push(p->second);
                p++;
            }
            if(canDo.empty()) break;
            w += canDo.top();
            canDo.pop();
        }
        return w;
    }
};